package models

import (
	_ "errors"
	"mongo/library/mongo"
	_ "time"

	"github.com/qiniu/qmgo"
	"go.mongodb.org/mongo-driver/bson"
)

// 激活码信息
type ActiveCode struct {
	ID          string `json:"id,omitempty"        bson:"_id,omitempty"`
	Code        string `json:"code"                bson:"code"`
	PartitionId int    `json:"partition_id,string" bson:"partition_id"`
	Actived     bool   `json:"actived"             bson:"actived"`
	StartTime   int64  `json:"start_time" bson:"start_time"` // 准入时间
	EndTime     int64  `json:"end_time" bson:"end_time"`     // 截至时间
}

// 数据库操作
const ACTIVE_CODE_LIST_COLLECTION_NAME = "active_code_list"

func GetActiveCodeListCollection() *qmgo.Collection {
	return mongo.GetCollection(ACTIVE_CODE_LIST_COLLECTION_NAME)
}

// 获取激活码列表
func GetActiveCodeList() ([]*ActiveCode, error) {
	list := make([]*ActiveCode, 0)
	err := mongo.Find(ACTIVE_CODE_LIST_COLLECTION_NAME, nil).All(&list)
	return list, err
}

// 分页获取
func GetActiveCodeByPage(pageSize int, pageNum int, condition bson.M) ([]*ActiveCode, error) {
	offset := (pageNum - 1) * pageSize
	list := make([]*ActiveCode, 0)
	err := GetActiveCodeListCollection().Find(mongo.GetContext(), condition).Sort("-actived", "start_time").Skip(int64(offset)).Limit(int64(pageSize)).All(&list)
	return list, err
}

// 获取总记录
func GetActiveCodeTotal(condition bson.M) (int64, error) {
	total, err := GetActiveCodeListCollection().Find(mongo.GetContext(), condition).Count()
	return total, err
}

// InsertActiveCode 插入激活码.
func InsertActiveCode(partition_id int, active_code string, start_time int64, end_time int64) error {
	record := &ActiveCode{}
	record.Code = active_code
	record.PartitionId = partition_id

	//转换时间为时间戳
	record.StartTime = start_time
	record.EndTime = end_time
	_, err := GetActiveCodeListCollection().InsertOne(mongo.GetContext(), record)
	return err
}

// 获取激活码
func ActiveCodeGet(id string) (*Code, error) {
	var code Code
	err := mongo.FindId(ACTIVE_CODE_LIST_COLLECTION_NAME, id, &code)
	if err != nil {
		return nil, err
	}
	return &code, nil
}

// 删除激活码
func ActiveCodeDel(id string) error {
	return mongo.RemoveId(ACTIVE_CODE_LIST_COLLECTION_NAME, id)
}

/*
*
获取激活码是否存在
*/
func ActiveCodeExist(code string) (int64, error) {
	return mongo.GetCount(ACTIVE_CODE_LIST_COLLECTION_NAME, bson.M{"code": code})
}

/*
*
更新激活码
*/
func UpDateActiveCode(id string, code string) error {
	return mongo.UpdateId(ACTIVE_CODE_LIST_COLLECTION_NAME, id, bson.M{"$set": bson.M{"code": code}})
}
